from datetime import datetime
import json
from time import timezone as t_time

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.shortcuts import render
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.contents.utils import get_categories
from apps.goods.utils import get_breadcrumb
from utils.response_code import RETCODE
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount


class ListView(View):
    '''商品列表页'''

    # 商品频道分类
    def get(self, request, category_id, page_num):

        sort = request.GET.get('sort', 'default')

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseBadRequest('发生错误')

        categories = get_categories()
        breadcrumb = get_breadcrumb(category)

        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = 'create_time'

        sku = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)

        paginator = Paginator(sku, 10)

        try:
            page_skus = paginator.page(page_num)
        except:
            return http.HttpResponseBadRequest('数据错误')
        total_page = paginator.num_pages

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sort': sort,
            'category': category,
            'page_skus': page_skus,
            'total_page': total_page,
            'page_num': page_num
        }

        return render(request, 'list.html', context)


class HotGoodsView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        hot_skus = []

        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'defalut_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'hot_skus': hot_skus})


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return render(request, '404.html')

        categories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)

        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []

        for spec in sku_specs:
            sku_key.append(spec.option.id)

        skus = sku.spu.sku_set.all()

        spec_sku_map = {}
        for s in skus:
            s_specs = s.specs.order_by('spec_id')

            key = []
            for spec in s_specs:
                key.append(spec.option.id)

            spec_sku_map[tuple(key)] = s.id

        goods_specs = sku.spu.specs.order_by('id')

        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            key = sku_key[:]
            spec_options = spec.options.all()
            for option in spec_options:
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))

            spec.spec_options = spec_options
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }

        return render(request, 'detail.html', context)


class DetailVisitView(View):
    def post(self, request, category_id):

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseBadRequest('数据错误')

        t = t_time.localtime()
        today_str = '%d-%02d-%02d' % (t.year, t.month, t.day)
        today_date = datetime.strptime(today_str, '%Y-%m-%d')

        try:
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            count_data = GoodsVisitCount()

        try:
            count_data.category = category
            count_data.count += 1
            count_data.save()
        except:
            return http.HttpResponseBadRequest('服务器错误')

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


class UserHistoryView(LoginRequiredMixin, View):
    def post(self, request):

        dict = json.loads(request.body.decode())
        sku_id = dict.get('sku_id')

        try:
            SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseBadRequest('sku不存在')

        conn = get_redis_connection('history')
        pl = conn.pipeline()
        user_id = request.user.id

        # 先去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 再存储
        pl.lpush('history_%s' % user_id, sku_id)
        # 最后截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行管道
        pl.execute()

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self, request):

        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % request.user.id, 0, -1)

        skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
